package cn.tedu.egweibo11.controller;

import cn.tedu.egweibo11.mapper.UserMapper;
import cn.tedu.egweibo11.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo11.pojo.dto.UserRegDTO;
import cn.tedu.egweibo11.pojo.entity.User;
import cn.tedu.egweibo11.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        /**
         * 注册功能
         * 1.用户名select占用
         * 2.插入注册数据
         */

        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);

        if(userVO!=null){
            return 2;
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());

        userMapper.insertUser(user);

        return 1;
    }

    @PostMapping("login")
    public int login (@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
        /**
         * 登录功能
         * 1.确认用户名select
         * 2.确认密码
         * 3.存入session key
         */

        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);

        if(userVO==null){
            return 3;
        }  //没有该用户名

        String password = userLoginDTO.getPassword();
        if(password.equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return 1;   //密码也正确，登录
        }

        return 2;

    }

    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        /**
         * 确认登录状态
         * 1.获取session key进行确认
         */
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        /**
         * 退出登录
         * 1.移除session key
         */
        session.removeAttribute("user");
        return "登出成功";
    }
}
